package com.mbc.common.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


import com.mbc.common.entities.UserInOffices;

public class UserInBranchesDAOImpls extends DAO<UserInOffices> implements UserInBranchesDAO {

	public UserInBranchesDAOImpls(Connection conn)
	{
		this.conn = conn;
		this.table_name = "UserInBranches";
	}

	@Override
	public void create(UserInOffices entity) throws SQLException {
		query = "insert into " + table_name + " ( userid, branchid) values( ?, ?)";
		pstmt = conn.prepareStatement(query);
		int i = 1;
		pstmt.setLong(i++, entity.getUserId());
		pstmt.setLong(i++, entity.getOfficeId());

		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	protected UserInOffices readRecord(ResultSet rs) throws SQLException {
		UserInOffices l_entity = new UserInOffices();
		l_entity.setAutoKey(rs.getLong("Autokey"));
		l_entity.setUserId(rs.getLong("UserId"));
		l_entity.setOfficeId(rs.getLong("branchid"));

		return l_entity;
	}

	@Override
	public void deleteByUserId(long userId) throws SQLException {
		query = getDeleteQuery() + " where userid = " + userId;
		pstmt = conn.prepareStatement(query);
		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	public ArrayList<UserInOffices> findByUserId(long userId)
			throws SQLException {
		ArrayList<UserInOffices> l_User_In_OfficeList = new ArrayList<UserInOffices>();
		query = getSelectQuery() + " where userid = " + userId;
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		while (rs.next()) {
			l_User_In_OfficeList.add(readRecord(rs));
		}
		rs.close();
		pstmt.close();
		return l_User_In_OfficeList;
	}
}
